9.1–9.2 Creating and accessing lists
1. What is a data structure? Name the built-in data structures in Python.
A data structure is a way of organising, managing and storing data for easy access and modification. Python's built-in data structures are lists, tuples, dictionaries and sets.
2. What is a list? List its features.
A list is an ordered collection of items stored under a single variable. The values are its elements.
- Ordered: elements stay in the order they were added and are retrieved by index.
- Heterogeneous: can hold different data types (numbers, strings, booleans, other lists, tuples, dictionaries).
- Dynamic: size can grow or shrink.
- Mutable: elements can be changed, added or removed after creation.
3. How is a list created? Give examples.
Enclose elements in square brackets separated by commas: list_name = [element1, element2, …].
scores = [85, 92, 78, 96, 88]
fruits = ["apple", "banana", "orange", "grape"]
my_bag = ["banana", 2, False, 7.25, "juice"] # heterogeneous
Internally, a list stores references to the element objects. Python tracks the number of references to each object and removes objects that are no longer referenced.
4. Write a program to create the lists favourite_games, favourite_books and student_heights and display them.
favourite_games = ["Chess", "Carrom", "Ludo"]
favourite_books = ["Wings of Fire", "Malgudi Days"]
student_heights = [152, 160, 158, 165, 149]
print(favourite_games)
print(favourite_books)
print(student_heights)5. How are list elements accessed? What happens if the index does not exist?
Use list_name[index]; indexing starts from 0.
fruits = ["apple", "banana", "orange", "grape"]
print(fruits[0]) # apple
print(fruits[2]) # orange
print(fruits[5]) # IndexError: list index out of range6. Explain negative indexing with L = [10,20,30,40,50].
Negative indices count from the end: the last element is –1, the second last –2, and so on. They let us reach elements from the end without knowing the length.
| Element | 10 | 20 | 30 | 40 | 50 |
|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 |
| Negative index | –5 | –4 | –3 | –2 | –1 |
L[-1] → 50; L[-2] → 40; L[-5] → 10.
7. Write a program to create a list of equipment in a Chemistry lab and print the last, second last and third last items.
equipment = ["beaker", "test tube", "burette", "pipette", "flask"]
print(equipment[-1]) # flask
print(equipment[-2]) # pipette
print(equipment[-3]) # burette9.3 List slicing
8. What is slicing? Give the syntax.
Slicing extracts a portion of a list: list_name[start:end]. It returns elements from start up to, but not including, end. If start is omitted the slice begins at the start; if end is omitted it continues to the end; if both are omitted, a new list containing all elements is returned. Negative indices can be used.
9. Find the output for colours = ["red","blue","green","yellow","purple"]: colours[1:4], colours[-3:4], colours[-3:], colours[:2].
| Slice | Output | Reason |
|---|---|---|
colours[1:4] | ['blue', 'green', 'yellow'] | Indices 1, 2, 3 |
colours[-3:4] | ['green', 'yellow'] | –3 is index 2 ("green"); stops before index 4 |
colours[-3:] | ['green', 'yellow', 'purple'] | From –3 to the end |
colours[:2] | ['red', 'blue'] | From the start up to index 1 |
10. How can slicing be used to replace elements? Evaluate L2 = [5,10,15,20,25]; L2[1:4] = [100,200,300].
Because lists are mutable, a slice can be assigned a new sequence. L2[1:4] selects 10, 15, 20, which are replaced by 100, 200, 300:
>>> print(L2)
[5, 100, 200, 300, 25]11. Explain slicing with a step value. Evaluate numbers[2:7:2] and numbers[9:0:-2] for numbers = [11,12,13,14,15,16,17,18,19,20].
Syntax: list_name[start:end:step]. The step is how many positions to move each time; a negative step moves backward.
numbers[2:7:2] → [13, 15, 17] (indices 2, 4, 6).
numbers[9:0:-2] → [20, 18, 16, 14, 12] (starts at index 9 and moves back by 2; index 0 is excluded).
12. What is a nested list? Give an example.
A list that contains other lists as elements. Nested lists represent tables, grids and matrices.
nested_list = [
[15, 4, 19, 84],
["Kasaragod", "Cherthala", "Mannarkkad"],
[2.5, 2.25, 4.2]
]The inner lists hold integers, strings and floats respectively.
13. Evaluate for numbers = [5,10,15,20,25,30,35,40] and letters = ['a','b','c','d','e','f','g']: (a) numbers[1:-2] (b) numbers[::-2] (c) letters[-5:-1:2]. What do you observe about negative values?
| Expression | Output | Reason |
|---|---|---|
(a) numbers[1:-2] | [10, 15, 20, 25, 30] | From index 1 to before index 6 (–2) |
(b) numbers[::-2] (also (d)) | [40, 30, 20, 10] | Whole list backward, every second element |
(c) letters[-5:-1:2] | ['c', 'e'] | –5 is index 2; stops before index 6; step 2 gives indices 2, 4 |
Negative start/end values count from the end of the list, and a negative step reverses the direction of selection.
14. For letters = ['a','b','c','d','e','f'], compare letters[3:0:-1] and letters[3:0:1].
letters[3:0:-1] → ['d', 'c', 'b']: the step is negative so it moves backward from index 3 to index 1 (index 0 excluded).
letters[3:0:1] → []: the step is positive but start (3) is greater than end (0), so nothing can be selected. Reverse selection needs a negative step.
15. Write a program to print the reverse of a list using negative indexing.
L = [10, 20, 30, 40, 50]
print(L[::-1]) # [50, 40, 30, 20, 10]9.4–9.5 Mutability and concatenation
16. What does it mean that lists are mutable? Explain with L2 = L1.
A list's elements can be changed after creation. A variable is just a reference to an object. After L1 = [10,20,30] and L2 = L1, both refer to the same list object, so changing one is visible through the other:
>>> L1[0] = 100
>>> print(L2)
[100, 20, 30]No new object is created; the existing one is modified.
17. What happens when a slice is extracted and assigned to another variable?
A new list object is created, so modifying it does not affect the original.
L1 = [10, 20, 30]
L2 = L1[0:2] # new list [10, 20]
L2[0] = 100
print(L1) # [10, 20, 30]
print(L2) # [100, 20]By contrast, slice assignment (L1[0:2] = [...]) changes the original list object.
18. What is concatenation of lists? Is the original list changed?
Joining two or more lists into one using +. A new list object is created; the original lists remain unchanged. Duplicates are preserved.
L1 = [10, 20, 30]
L2 = [40, 50]
L3 = L1 + L2
print(L3) # [10, 20, 30, 40, 50]If two class lists both contain "Asha", the combined list contains "Asha" twice.
9.6 List functions and operations
19. Explain the membership operators with examples.
in is True if an element is present in the list; not in is True if it is absent.
solar_planets = ["Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune"]
print("Uranus" in solar_planets) # True
print("Pluto" in solar_planets) # False
print("Pluto" not in solar_planets) # True20. Explain append(), insert(), pop() and remove() with examples.
| Method | Description | Example and result |
|---|---|---|
append(x) | Adds an item to the end of the list | fibonacci.append(8) → [1, 1, 2, 3, 5, 8] |
insert(i, x) | Inserts x at index i | colours.insert(2, "black") → ['red','blue','black','green','yellow','purple'] |
pop(i) | Removes and returns the element at index i; the last element if no index is given | colours.pop(3) returns 'green' |
remove(x) | Removes the first occurrence of x | colours.remove("blue") → ['red','black','yellow','purple'] |
21. Differentiate between pop() and remove().
pop() removes an element by its position and returns it; with no argument it removes the last element. remove() removes the first occurrence of a given value and returns nothing.
22. Explain len() and del.
len(list) returns the number of elements: len(colours) → 5.
del deletes an element or a slice without returning it, and can delete the whole list:
colours = ["red","blue","green","yellow","purple"]
del colours[3]
print(colours) # ['red', 'blue', 'green', 'purple']23. Write a program that accepts a few integers from the user, appends them to a list and prints the list.
numbers = []
n = int(input("How many numbers? "))
for i in range(n):
x = int(input("Enter number: "))
numbers.append(x)
print("The list is:", numbers)9.7 Traversing a list
24. What is list traversal? Explain direct traversal.
Traversal is visiting each element of a list to count, update or check conditions. In direct traversal a for loop assigns each element to a variable in turn:
expenses = [250, 400, 120, 90]
for expense in expenses:
print(expense)It works well when we only need to read or check elements.
25. Write a program to count the students who scored below 40 in marks = [55,72,38,90,25,67,48,33,17,12,60].
marks = [55, 72, 38, 90, 25, 67, 48, 33, 17, 12, 60]
count = 0
for mark in marks:
if mark < 40:
count += 1
print('Number of students who scored below 40:', count)Output: Number of students who scored below 40: 5 (38, 25, 33, 17, 12).
26. What is index-based traversal? When is it needed?
The loop runs over index values generated by range(len(list)). It is needed when we want to modify elements or know their positions (iteration by position).
marks = [55, 72, 38, 90, 25, 17, 48, 33, 27, 12, 60]
pass_mark = 25
for i in range(len(marks)):
if marks[i] < pass_mark:
print("Sl.No.", i + 1, "Failed")Output: Sl.No. 6 Failed and Sl.No. 10 Failed. range(len(marks)) gives indices 0 to 10, and i + 1 gives the serial number.
27. Increase prices below 150 by 10% by traversing the list (Figure 9.18).
price = [280, 380, 75, 110, 300, 475, 500, 150, 600, 525]
print("Initial price list:", price)
for i in range(len(price)):
if price[i] < 150:
price[i] = price[i] + price[i] * 0.10
print("Final price list:", price)Only 75 and 110 are below 150, becoming 82.5 and 121.0; the other prices stay the same.
28. Write the function update_price() (Figure 9.19): prices below 200 increase by 10%, prices of 500 or above decrease by 5%, others unchanged.
def update_price(price_list):
for i in range(len(price_list)):
if price_list[i] < 200:
price_list[i] = price_list[i] + price_list[i] * 0.10
elif price_list[i] >= 500:
price_list[i] = price_list[i] - price_list[i] * 0.05
return price_list
price = [200, 300, 75, 110, 300, 475, 500, 150, 600, 525]
print("Initial Prices:", price)
new_price = update_price(price)
print("Updated Prices:", new_price)Output: [200, 300, 82.5, 121.0, 300, 475, 475.0, 165.0, 570.0, 498.75]. Note that price and new_price refer to the same list object, since the list was modified in place.
29. Explain the output of the program data = [5,10,15] / for i in range(len(data)): data[i] = data[i]*2 / print(data) (with print inside the loop).
The loop doubles one element per iteration (index-based) and prints the whole list each time:
[10, 10, 15] # i = 0: 5 doubled to 10
[10, 20, 15] # i = 1: 10 doubled to 20
[10, 20, 30] # i = 2: 15 doubled to 30The list is modified in place, so each print shows the changes made so far.
30. Predict the output if data = [5, 10, 15, 20], and explain how the list changes.
[10, 10, 15, 20]
[10, 20, 15, 20]
[10, 20, 30, 20]
[10, 20, 30, 40]In each iteration one more element (at index 0, 1, 2, 3) is doubled, so four lines are printed and the final list has all elements doubled.
31. Write ReadList() and PrintList(L), and a main program that reads names until "None" is entered.
def ReadList():
L = []
while True:
item = input("Enter item (None to stop): ")
if item == "None":
break
L.append(item)
return L
def PrintList(L):
for item in L:
print(item)
L = ReadList()
if L:
PrintList(L)
else:
print("No data in the list")Entering only "None" returns an empty list, so "No data in the list" is shown. Save the two functions in MyListModule.py to reuse them.
32. Extend it: read a list, then repeatedly replace the k-th element or append a new one.
from MyListModule import ReadList, PrintList
L = ReadList()
PrintList(L)
while True:
k = input("Enter index (non-positive or non-number to stop): ")
if not k.isdigit() or int(k) <= 0:
break
k = int(k)
s = input("Enter data: ")
if k <= len(L):
L[k - 1] = s # replace the k-th element
else:
L.append(s)
PrintList(L)
print("Thank you")With input apple, mango, banana: entering k = 2 and "jackfruit" replaces mango; entering k = 5 and "orange" appends orange.
33. Write OddList() and FindSmallest(); test with 3, 7, 8, 9, 15.
def OddList(L):
count = 0
for x in L:
if isinstance(x, int) and x % 2 != 0:
count += 1
if count == 0:
return None
return count
def FindSmallest(L):
smallest = None
for x in L:
if isinstance(x, (int, float)):
if smallest is None or x < smallest:
smallest = x
return smallest
L = [3, 7, 8, 9, 15]
odd = OddList(L)
print("Odd numbers:", odd) # 4
print("Even numbers:", len(L) - (odd or 0)) # 1
print("The smallest number in the list is:", FindSmallest(L)) # 3The built-in isinstance() checks whether an element is an integer. Even numbers are the total count minus the odd count.
9.8.1 Linear search
34. What is searching? Explain linear search.
Searching is finding whether a particular element exists in a collection and, if so, its position. Linear (sequential) search checks the elements one by one from the first until the target is found or the end of the list is reached. For the list 50, 18, 48, 35, 45, 26, 12 and target 45, it compares 50, 18, 48, 35 and finds 45 at the 5th position.
35. Write the algorithm for linear search.
Step 1: Start
Step 2: Accept N, the number of elements
Step 3: Accept N elements into LIST
Step 4: Accept the value to be searched in ITEM
Step 5: Set LOC = –1
Step 6: Starting from the first position, repeat Step 7 until the last element
Step 7: If ITEM equals the element at the current position, store the position in LOC and go to Step 8; otherwise move to the next position
Step 8: If LOC < 0 display "Not Found", else display LOC + 1 as the position
Step 9: Stop
Flowchart: Start → Input N, LIST, ITEM → LOC = –1, i = 0 → decision "i < N?" (False → go to the result check) → decision "LIST[i] == ITEM?" (True → LOC = i, exit loop; False → i = i + 1 and back to the first decision) → decision "LOC < 0?" → Print "Not Found" or Print LOC + 1 → Stop.
36. Write a Python program for linear search using a function.
def linear_search(LIST, ITEM):
for i in range(len(LIST)):
if LIST[i] == ITEM:
return i
return -1
N = int(input("Enter number of elements: "))
LIST = []
for i in range(N):
LIST.append(int(input("Enter element: ")))
ITEM = int(input("Enter the item to search: "))
LOC = linear_search(LIST, ITEM)
if LOC < 0:
print("Not Found")
else:
print("Found at position", LOC + 1)For 50, 18, 48, 35, 45, 26, 12 searching 45 prints Found at position 5.
9.8.2–9.8.4 Matrices
37. What is a matrix? How is it represented using lists? What is the order of a matrix?
A matrix is a rectangular arrangement of values in rows and columns. It is represented by a nested list in which each inner list is a row and all inner lists have the same length. The order is written m × n (rows × columns).
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]] # a 3 x 3 matrix38. Write a program to display a matrix in row-column form.
for row in matrix:
for item in row:
print(item, end=" ")
print()The outer loop takes each row; the inner loop prints that row's elements on one line; the empty print() moves to the next line.
39. How are elements of a matrix accessed? Find matrix[0][0], matrix[1][2], matrix[2][1] for the 3 × 3 matrix above.
Use matrix[row][column]; the row comes first and numbering starts from 0.
matrix[0][0] → 1; matrix[1][2] → 6; matrix[2][1] → 8.
40. Write functions accept_matrix() and print_matrix().
def accept_matrix():
rows = int(input("Enter number of rows: "))
cols = int(input("Enter number of columns: "))
matrix = []
for i in range(rows):
row = []
for j in range(cols):
row.append(int(input(f"Enter element [{i}][{j}]: ")))
matrix.append(row)
return matrix
def print_matrix(matrix):
for row in matrix:
for item in row:
print(item, end=" ")
print()
m = accept_matrix()
print_matrix(m)For a 2 × 3 matrix with inputs 10 to 60, row grows [10], [10, 20], [10, 20, 30], which is appended to matrix; then a new row is built as [40], [40, 50], [40, 50, 60]. The final matrix is [[10, 20, 30], [40, 50, 60]].
41. What is the condition for adding two matrices? Write the program for matrix addition.
Two matrices can be added only if they have the same order (same number of rows and columns). Corresponding elements are added.
def add_matrices(mat1, mat2):
rows = len(mat1)
cols = len(mat1[0])
result = []
for i in range(rows):
row = []
for j in range(cols):
row.append(mat1[i][j] + mat2[i][j])
result.append(row)
return result
mat1 = accept_matrix()
mat2 = accept_matrix()
if len(mat1) == len(mat2) and len(mat1[0]) == len(mat2[0]):
print_matrix(add_matrices(mat1, mat2))
else:
print("Matrices cannot be added: orders differ")The if compares the number of rows (len(mat1), len(mat2)) and columns (len(mat1[0]), len(mat2[0])).
42. What are the diagonal elements of a matrix? Write a program to print them.
The main diagonal runs from the top-left to the bottom-right corner, at positions where the row index equals the column index, [i][i]. Diagonal elements exist for square matrices.
import random
def generate_matrix():
while True:
rows = int(input("Enter number of rows: "))
cols = int(input("Enter number of columns: "))
if rows == cols:
break
print("Rows and columns must be equal. Enter again.")
matrix = []
for i in range(rows):
row = []
for j in range(cols):
row.append(random.randint(1, 50))
matrix.append(row)
return matrix
def print_diagonal(matrix):
for i in range(len(matrix)):
print(matrix[i][i], end=" ")
print()
m = generate_matrix()
print_matrix(m)
print_diagonal(m)random.randint(1, 50) generates a random integer from 1 to 50. Computers simulate randomness with a Pseudo-Random Number Generator, which produces a long sequence of numbers that appear random but come from an algorithm.
9.8.5 Recursion with lists
43. Write a recursive function to reverse a list. Explain the logic.
def reverse_list(nums):
if len(nums) <= 1: # base case
return nums
return reverse_list(nums[1:]) + [nums[0]]
n = int(input("Enter the size of the list: "))
numbers = []
for i in range(n):
numbers.append(int(input("Enter number: ")))
print("Original list:", numbers)
print("Reversed list:", reverse_list(numbers))
The base case is a list with zero or one element, which is returned as it is. Otherwise nums[1:] (all elements except the first) is reversed recursively, and the first element [nums[0]] is placed at the end using +. For [1, 2, 3]: reverse([2, 3]) + [1] = (reverse([3]) + [2]) + [1] = [3] + [2] + [1] = [3, 2, 1].
Practice programs (Let us do)
44. Collect n numbers, calculate their average, and display the numbers greater than the average (use functions).
def read_numbers(n):
L = []
for i in range(n):
L.append(float(input("Enter number: ")))
return L
def average(L):
return sum(L) / len(L)
def above_average(L, avg):
for x in L:
if x > avg:
print(x, end=" ")
print()
n = int(input("How many numbers? "))
nums = read_numbers(n)
avg = average(nums)
print("Average =", avg)
above_average(nums, avg)45. Calculate the average of all elements of a matrix and display those greater than the average.
def calculate_matrix_average(matrix):
total = 0
count = 0
for row in matrix:
for x in row:
total += x
count += 1
return total / count
def display_elements_above_average(matrix, avg):
for row in matrix:
for x in row:
if x > avg:
print(x, end=" ")
print()
m = accept_matrix()
avg = calculate_matrix_average(m)
print("Average =", avg)
display_elements_above_average(m, avg)46. Find the transpose of a matrix.
The transpose swaps rows and columns: element [i][j] becomes [j][i]. An m × n matrix becomes n × m.
def transpose(matrix):
rows = len(matrix)
cols = len(matrix[0])
result = []
for j in range(cols):
row = []
for i in range(rows):
row.append(matrix[i][j])
result.append(row)
return result
m = accept_matrix()
print_matrix(transpose(m))Example: [[1, 2, 3], [4, 5, 6]] becomes [[1, 4], [2, 5], [3, 6]].
47. What is a symmetric matrix? Write a program to check whether a square matrix is symmetric.
A square matrix A is symmetric if it equals its transpose (A = AT), i.e. element [i][j] equals element [j][i] for all i, j.
def is_symmetric(A, AT):
return A == AT # lists compare element by element
m = accept_matrix() # must be a square matrix
if len(m) == len(m[0]) and is_symmetric(m, transpose(m)):
print("Symmetric matrix")
else:
print("Not a symmetric matrix")Example: [[1, 2], [2, 3]] is symmetric; [[1, 2], [3, 4]] is not.
48. Find the trace of a square matrix.
The trace tr(A) is the sum of the elements on the main diagonal.
def calculate_trace(matrix):
total = 0
for i in range(len(matrix)):
total += matrix[i][i]
return total
m = accept_matrix()
print("Trace =", calculate_trace(m))For [[1, 2, 3], [4, 5, 6], [7, 8, 9]] the trace is 1 + 5 + 9 = 15.
49. Demonstrate matrix-scalar addition and subtraction on a random N × M matrix (values 0 to 100).
import random
def random_matrix(n, m):
return [[random.randint(0, 100) for j in range(m)] for i in range(n)]
def read_scalar():
return int(input("Enter a scalar value: "))
def add_scalar(matrix, s):
return [[x + s for x in row] for row in matrix]
def subtract_scalar(matrix, s):
return [[x - s for x in row] for row in matrix]
def display(matrix):
for row in matrix:
print(*row)
n = int(input("Rows: "))
m = int(input("Columns: "))
A = random_matrix(n, m)
s = read_scalar()
print("Original matrix:"); display(A)
print("After addition:"); display(add_scalar(A, s))
print("After subtraction:"); display(subtract_scalar(A, s))50. Fill in the blanks / one-word answers.
- A list is created using ______ brackets: square.
- Index of the first element: 0; index of the last element: –1.
- Error raised for a non-existent index: IndexError.
- Operator used to join lists: +.
- Method to add an element at a given index: insert().
- Statement that deletes an element or slice without returning it: del.
- Search technique that checks elements one by one: linear (sequential) search.
- Element address in a matrix: matrix[row][column].
- Module used for
randint(): random.